﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Web.UI.WebControls;
using System.Threading;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using Nivdal.AuxCode;
using System.Text;

namespace Nivdal
{
    public partial class AddStory : System.Web.UI.Page
    {
        private string TeamuploadDirectory;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
                Response.Redirect("~/Default.aspx");
            OnlineUser ou = (OnlineUser)Session["User"];
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();

            string country = ou.Country;
            string UserNewsPaperPriv = GND.ReadNivdalIntData("UserId", "Nivdal_GetNewsPaperPrivsLevel", ou.UserId);
            
            //Response.Write("UserNewsPaperPriv is: " + UserNewsPaperPriv);
            if (UserNewsPaperPriv != "2" && UserNewsPaperPriv != "3")
                Response.Redirect("default.aspx");
            if (!IsPostBack)
                this.RubricsSqlDataSource.SelectParameters.Add("UserId", ou.UserId);

            //place files in website subfolder named NewsPaper
            TeamuploadDirectory = Path.Combine(
               Request.PhysicalApplicationPath, "Images/NewsPaper");
            this.Title = Resources.Resource.Default_PageTitle + ", " + Resources.Resource.AddStory_PageTitle;

            //TextHelpLabel.Text = GlobalFunctions.EditorHelp();
            //if (Request.QueryString["NewsPaperId"] != null)
            //{
            //    string NewsPaperId = Request.QueryString["NewsPaperId"];
            //    this.RubricsSqlDataSource.SelectParameters.Add("NewsPaperId", NewsPaperId);
            //}

        }

        public enum ResizeOptions
        {
            // Use fixed width & height without keeping the proportions
            ExactWidthAndHeight,

            // Use maximum width (as defined) and keeping the proportions
            MaxWidth,

            // Use maximum height (as defined) and keeping the proportions
            MaxHeight,

            // Use maximum width or height (the biggest) and keeping the proportions
            MaxWidthAndHeight
        }

        public static System.Drawing.Bitmap DoResize(System.Drawing.Bitmap originalImg, int widthInPixels, int heightInPixels)
        {
            System.Drawing.Bitmap bitmap;
            try
            {
                bitmap = new System.Drawing.Bitmap(widthInPixels, heightInPixels);
                using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap))
                {
                    // Quality properties
                    graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                    graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

                    graphic.DrawImage(originalImg, 0, 0, widthInPixels, heightInPixels);
                    return bitmap;
                }
            }
            finally
            {
                if (originalImg != null)
                {
                    originalImg.Dispose();
                }
            }
        }

        public static System.Drawing.Bitmap ResizeImage(System.Drawing.Bitmap image, int width, int height, ResizeOptions resizeOptions)
        {
            float f_width;
            float f_height;
            float dim;
            switch (resizeOptions)
            {
                case ResizeOptions.ExactWidthAndHeight:
                    return DoResize(image, width, height);

                case ResizeOptions.MaxHeight:
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_height <= height)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;
                    width = (int)((float)(height) * dim);
                    return DoResize(image, width, height);

                case ResizeOptions.MaxWidth:
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_width <= width)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;
                    height = (int)((float)(width) / dim);
                    return DoResize(image, width, height);

                case ResizeOptions.MaxWidthAndHeight:
                    int tmpHeight = height;
                    int tmpWidth = width;
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_width <= width && f_height <= height)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;

                    // Check if the width is ok
                    if (f_width < width)
                        width = (int)f_width;
                    height = (int)((float)(width) / dim);
                    // The width is too width
                    if (height > tmpHeight)
                    {
                        if (f_height < tmpHeight)
                            height = (int)f_height;
                        else
                            height = tmpHeight;
                        width = (int)((float)(height) * dim);
                    }
                    return DoResize(image, width, height);
                default:
                    return image;
            }
        }



        public System.Drawing.Bitmap ResizeImgFile(System.Drawing.Bitmap img)
        {

            int width = 150;
            int height = 150;
            System.Drawing.Bitmap ResizedImg = ResizeImage(img, width, height, ResizeOptions.MaxWidthAndHeight);
            return ResizedImg;

        }


        public bool CheckImgFile(string FileExtantion)
        {

            if (FileExtantion.Equals(".jpg") || (FileExtantion.Equals(".gif")) || (FileExtantion.Equals(".bmp")) || (FileExtantion.Equals(".png")))
                return true;
            else
                return false;
        }

        protected void AddStory_Click(object sender, EventArgs e)
        {
            Random rnd = new Random();
            string num = DateTime.Now.Year.ToString() + DateTime.Now.DayOfYear.ToString() +
            DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() +
            DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
            int intFileSizeLimit = 2000;
            bool IsImageInput = false;
            string extension = Path.GetExtension(imgUpload.PostedFile.FileName);
            string filenameNoExtension = Path.GetFileNameWithoutExtension(imgUpload.PostedFile.FileName);
            string ServerfileName = num + extension;
            string FullUploadPath = Path.Combine(TeamuploadDirectory, ServerfileName);
            string FileExtantion = (Path.GetExtension(imgUpload.FileName).ToLower());
            string ImagePath = "~/Images/NewsPaper/" + ServerfileName;
            if (!(imgUpload.HasFile && imgUpload.PostedFile != null))//first check if the user uploaded file
            {
                IsImageInput = false;//There is no image file
                ImagePath = "~/images/newspaper/pic2.jpg"; //default image
            }
            else //There is an image input
                IsImageInput = true;
            //check if the image file has the right extantion and size
            if (IsImageInput && CheckImgFile(FileExtantion) && imgUpload.PostedFile.ContentLength / 1024 < intFileSizeLimit)
            {
                System.Drawing.Bitmap ResizedUserPicture = ResizeImgFile(new System.Drawing.Bitmap(imgUpload.PostedFile.InputStream));
                try
                {
                    ResizedUserPicture.Save(FullUploadPath);

                }
                catch (Exception err)
                {
                    this.MessageLabel.Text = err.Message;
                    IsImageInput = false;
                }
            }

            else
            {
                if (IsImageInput)
                    MessageLabel.Text = Resources.Resource.Preferences_LeftImageFileError + " " + intFileSizeLimit + Resources.Resource.Preferences_RightImageFileError;

            }


            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            string title = this.StoryTitleTextBox.Text.Trim();
            string subtitle = this.SubTitleTextBox.Text.Trim();
            string Rubric = this.RubricsDropDownList.SelectedValue;
            string Text = this.Storyeditor.Text.Trim();
            string image = ImagePath;// "/images/newspaper/pic2.jpg";
            //ShowPopUpMsg(image + " " + IsImageInput.ToString());

            // Response.Redirect("Default.aspx");
            string returnValue = GND.ReadNivdalIntData("RubricId", "UserId", "Title", "SubTitle", "text", "image", "OriginalText",
                "Nivdal_AddNewStory", Rubric, ou.UserId, title, subtitle, "", image, "");

            GlobalFunctions.AddStoryText(returnValue, Text, false);

            Response.Redirect("~/Story.aspx?StoryId=" + returnValue);          
            
        }

        private void ShowPopUpMsg(string msg)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("alert('");
            sb.Append(msg.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'"));
            sb.Append("');");
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "showalert", sb.ToString(), true);
        }

        protected override void InitializeCulture()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            this.PreviewLabel.Text = GlobalFunctions.EncodeHtmlFromText(this.Storyeditor.Text.Trim());
        }
    }
}